<?php
	// Start session
	session_start();
	
	if (isset($_SESSION['captcha_time']))
	{
		if (time() - $_SESSION['captcha_time'] < 3)
			die();
	}
	
	$_SESSION['captcha_time'] = time();
	
	function genRandomString($length = 6) {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
		$random = '';    

		for ($p = 0; $p < $length; $p++) {
			$random .= $characters[mt_rand(0, strlen($characters))];
		}

		return $random;
	}
	
	function getNewCaptcha($length = 6, $fontSize = 6)
	{
		header("Content-type: image/png");
		
		$random = genRandomString($length);
		$_SESSION['svdm_captcha_hash'] = md5($random);
		$width = imagefontwidth($fontSize)* strlen($random) + 6;
		$height = imagefontheight($fontSize) + 6;
		$im  = imagecreatetruecolor($width, $height);
		$bgc = imagecolorallocate($im, 0, 0, 0);
		$tc  = imagecolorallocate($im, 255, 255, 255);
		imagefilledrectangle($im, 0, 0, $width, $height, $bgc);
		imagestring($im, $fontSize, 3, 3, $random, $tc);
		imagepng($im);
	}
	
	
	$length = isset($_GET['length']) ? intval($_GET['length']) : 6;
	getNewCaptcha($length);
